<?php
/*
 * @Author: crg
 * @Date: 2024-05-12 10:56:51
 * @LastEditors: zwx
 * @LastEditTime: 2024-09-06 16:19:57
 * @Description: 私域直播    -订单列表
 */

namespace app\apiadmin\controller\live;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\service\deposit\DepositService;
use app\apiadmin\service\order\OrderService;
use app\apiadmin\service\statics\LiveUserGetDataService;
use app\apikanke\controller\student\Student;
use app\common\controller\BaseController;
use app\common\utils\Res;
use app\Request;
use DateTime;
use DateTimeZone;
use MongoDB\BSON\ObjectId;
use think\facade\Db;

class MyOrder extends BaseController
{

    /**
     * @author: crg
     * @Description: 获取app订单列表数据
     * @Date: 2024-05-12 11:00:52
     */
    public function getMyOrderData()
    {
        $param = $this->request->param();

        $result = OrderService::getMyOrder($param);
        return $result;

    }
    public function getDepositData()
    {
        $param = $this->request->param();
        $deposit_service = \app\apiadmin\service\deposit\DepositService::getInstance();
        $result = $deposit_service->list($param);

        return Res::ok($result);
    }

    /**
     * @author: zwx
     * @Description: 获取app订单详情数据
     * @Date: 2024-05-12 11:00:52
     */
    public function getMyOrderInfo()
    {
        $param = $this->request->param();
        $type = '';
        if (isset($param['type']) && !empty($param['type'])) {
            $type = $param['type'];
        }
        if ($type == 'deposit') { //定金信息
            $res = DepositService::getInstance()->info($param);
            if ($res) {
                $res['order_num'] = $res['deposit_num'];
                $res['pay_method'] = $res['pay_method'] == 1 ? '微信' : '支付宝';
            }
            $data = [
                'datas' => [$res],
            ];
            $result = Res::ok($data);
        } else {
            $result = OrderService::getMyOrderInfo($param);
        }
        return $result;

    }

    /**
     * @author: crg
     * @Description: app订单支付保存
     * @Date: 2024-05-12 11:00:52
     */
    public function payOrder()
    {
        $param = $this->request->param();
        $id = $param['id'];
        $remark = $param['remark'];
        $pay_method = $param['pay_method'];

        $courseid = $param['courseid'];
        $coursename = $param['coursename'];
        $fee = $param['fee'];
        $wx_openid = $param['openid'];
        $order_num = $param['ordernum'];
        $liveId = $param['liveId'];

        $data = array();
        if ($remark && $remark != '') {
            $data['remark'] = $remark;
        }
        if ($pay_method && $pay_method != '') {
            $data['pay_method'] = $pay_method;
        }
        // 获取当前的时间戳和随机数
        $timestamp = time();
        // $randomNum = mt_rand(100000, 999999);
        // $prefix = 'SY';
        // 组合订单号前缀和序列号
        // $orderNumber = $prefix . $timestamp . str_pad($randomNum, 6, '0', STR_PAD_LEFT);
        // $data['order_num'] = $orderNumber;

        // $data['state'] = 1;

        $data['order_num'] = 'SY' . $param['order_from'] . rand(1000, 9999) . date('YmdHis', $timestamp);

        $dd = DB::table('xh_siyu_order')->where(array('id' => $id))->find();
        if ($dd) {
            $a = DB::table('xh_siyu_order')->where(array('id' => $id))->update($data);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

        $account = UnionAppFuWuShang::getFuWuShangAccount($pay_method); //账户信息

        $data = array();
        // if ($pay_method == 1) {
        // $data = UnionApp::createPrepayId($wx_openid, $fee, $coursename, $courseid, $order_num, $timestamp, $liveId, '', '');
        $data = UnionAppFuWuShang::createPrepayId($account, $wx_openid, $fee, $coursename, $courseid, $order_num, $timestamp, $liveId, '', '');
        // }

        return Res::ok($data);

    }

    /**
     * @author: crg
     * @Description: app创建订单支付保存
     * @Date: 2024-05-12 11:00:52
     */
    public function createPayOrder()
    {
        $param = $this->request->param();
        $key = isset($param['key']) ? $param['key'] : '';
        $deposit_ids = isset($param['deposit_ids']) ? $param['deposit_ids'] : [];
        // 获取当前的时间戳和随机数
        $timestamp = time();
        $randomNum = mt_rand(100000, 999999);
        $prefix = 'SY';
        // 组合订单号前缀和序列号
        $orderNumber = $prefix . $timestamp . str_pad($randomNum, 6, '0', STR_PAD_LEFT);

        $remark = $param['remark'];
        $user_id = $param['user_id'];
        $wx_openid = isset($param['openid']) ? $param['openid'] : '';
        $wx_unionid = isset($param['unionid']) ? $param['unionid'] : '';
        $pay_method = $param['pay_method']; // 支付方式
        $courseid = $param['courseid'];
        $coursename = $param['coursename'];
        $order_from = $param['order_from']; //订单来源
        $tel = $param['tel']; //手机号
        $fee = $param['fee']; //金额
        $liveId = $param['liveId']; //直播id
        $from = !empty($liveId) ? 0 : 1;

        $account = UnionAppFuWuShang::getFuWuShangAccount($param['pay_method']); //账户信息

        $data = array();
        $data['remark'] = $remark;
        $data['user_id'] = $user_id;
        $data['create_time'] = date('Y-m-d H:i:s', $timestamp);
        $data['order_from'] = $order_from;
        $data['tel'] = $tel;
        $data['fee'] = $fee;
        $data['order_num'] = $orderNumber;
        $data['wx_openid'] = $wx_openid;
        $data['wx_unionid'] = $wx_unionid;
        $data['pay_method'] = $pay_method;
        $data['courseid'] = $courseid;
        $data['liveId'] = $liveId;
        $data['tutorId'] = $param['tutorId'];
        $data['from'] = $from;
        $data['key'] = $key;
        $data['deposit_ids'] = implode(',', $deposit_ids);

        $data['sub_mchid'] = $account['sub_mchid'];
        $data['accountid'] = $account['id'];

        $id = DB::table('xh_siyu_order')->insertGetId($data);

        //统计提单数据
        $liveStatus = new LiveStatus($liveId);
        $liveStatus->set_xiaoshoue_weifukuan($fee);
        $liveStatus->set_xiadan_danshu_weifukuan($orderNumber);
        $liveStatus->set_xiadan_renshu_weifukuan($user_id);

        //行为记录添加数据详情
        // $collection = 'live_order';
        // $liveOrder = new LiveUserGetDataService($collection);
        // $map = [];
        // $map['user_id'] = $user_id.'';
        // $map['order_num'] = $orderNumber;
        // $map['wx_unionid'] = $wx_unionid;
        // $map['state'] = 0;
        // $map['del'] = 0;
        // $map['pay_time'] = '';
        // $map['pay_method'] = $pay_method;
        // $map['tel'] = $tel;
        // $map['fee'] = number_format($fee/100,2);
        // $map['create_time'] = date('Y-m-d H:i:s', $timestamp);
        // $map['order_from'] = $order_from;
        // $map['remark'] = $remark;
        // $map['courseid'] = $courseid;
        // $map['coursename'] = $coursename;
        // $map['liveId'] = $liveId;
        // $data = $liveOrder->addOderInfo($map);

        //生成微信预下单id
        $event_id = '';
        if (isset($param["event_id"])) {
            $event_id = $param["event_id"];
        }

        $data = array();
        if ($pay_method == 1) {
            // $data = UnionApp::createPrepayId($wx_openid, $fee, $coursename, $courseid, $orderNumber, $timestamp, $liveId, $user_id, $event_id);
            $data = UnionAppFuWuShang::createPrepayId($account, $wx_openid, $fee, $coursename, $courseid, $orderNumber, $timestamp, $liveId, $user_id, $event_id);
        }

        if (!is_array($data)) {
            return $data;
        }

        $data['orderid'] = $id;

        //行为记录添加数据详情
        if ($event_id != '') {
            $collection = 'live_event';
            $liveOrder = new LiveUserGetDataService($collection);
            $map = [];
            $map['_id'] = new ObjectID($param["event_id"]);

            $update = ['$set' => ['event' => '提单未付款']];

            $r = $liveOrder->updateEvent($map, $update);
        }

        return Res::ok($data);
    }

    public function createPrepayId()
    {

        // return Res::ok(file_get_contents('/data/siyu/app/apiadmin/keys/apiclient_key.pem'));

        $param = $this->request->post();

        $time = time();
        // 创建DateTime对象
        $dateTime = new DateTime(date('Y-m-d H:i:s', $time));

        // 设置时区，如果需要的话
        $dateTime->setTimezone(new DateTimeZone('Asia/Shanghai'));

        // 生成RFC3339格式的时间字符串
        $time_expire = $dateTime->format(DateTime::RFC3339);

        $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi';

        $amount = array();
        $amount['total'] = 1;
        $amount['currency'] = 'CNY';

        $payer = array();
        $payer['openid'] = $param['openid'];
        // $payer['openid'] = 'o7U8F6uxgFin-5j3aYfDHvwfyO2c';

        $json = array();
        $json['appid'] = 'wx6d35f289e388fcdc';
        $json['mchid'] = '1674971019';
        $json['notify_url'] = 'http://liveapi.banxued.com/apiadmin/unionapp/notify';

        $json['description'] = '测试商品';
        $json['out_trade_no'] = 'SY20240519153300012';
        $json['time_expire'] = $time_expire;
        $json['attach'] = 'courseid=1';

        $json['amount'] = $amount;
        $json['payer'] = $payer;

        //获取prepay_id
        $result = self::client_post($url, $json);

        if ($result['code'] != 200) {
            return Res::error($result);
        }

        //组合数据
        $data = array();
        $data['appId'] = $json['appid'];
        $data['timeStamp'] = $time;
        $data['nonceStr'] = self::getRandomString(32);
        $data['package'] = 'prepay_id=' . json_decode($result['body'], true)['prepay_id'];
        $data['signType'] = 'RSA';
        $data['paySign'] = self::makeSign($data['appId'], $data['timeStamp'], $data['nonceStr'], $data['package']); //签名，使用字段AppID、timeStamp、nonceStr、package计算得出的签名值

        return Res::ok($data);
    }

    /**
     * @author: crg
     * @Description: app订单取消
     * @Date: 2024-05-12 11:00:52
     */
    public function cancelOrder()
    {
        $param = $this->request->param();
        $id = $param['id'];
        $state = $param['state'];
        $data = array();
        if ($state && $state != '') {
            $data['state'] = $state;
        }
        $dd = DB::table('xh_siyu_order')->where(array('id' => $id))->find();
        if ($dd) {
            $a = DB::table('xh_siyu_order')->where(array('id' => $id))->update($data);

            //更新行为记录添加数据详情
            // $collection = 'live_order';
            // $map = [];
            // $map['liveId'] = $dd['liveId'];
            // $map['order_num'] = $dd['order_num'];

            // $update = ['$set' => ['state' => 4]];
            // $liveOrder = new LiveUserGetDataService($collection);
            // $liveOrder->updateOrder($map, $update);

            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

        return Res::ok($id);
    }

    /**
     * @author: crg
     * @Description: test测试
     * @Date: 2024-05-12 11:00:52
     */
    public function test()
    {
        //测试代码小段  测试通过以后删除
        $param = $this->request->post();
        $remark = $param['remark'];

        $d['remark'] = $remark . '我是有opend，数据库也有记录的情况';
        $id = DB::table('xh_siyu_user_remark')->save($d);

        return Res::ok($id);
    }

    public static function afterPayOrder($orderInfo)
    {

        /**
         * @var Student $studentControl
         */
        $studentControl = app(Student::class);
        $params = [];
        $params['order_no'] = $orderInfo['order_num'];
        $params['sy_order_type'] = 1;
        $params['sy_order_num'] = 1;

        // 这里 是 订单
        $params['account'] = $orderInfo["tel"];
        $params["course_id"] = $orderInfo["courseid"];
        $params["unionid"] = $orderInfo["wx_unionid"];

        $ret = $studentControl->openAdd($params);

        $code = $ret["code"];
        $msg = $ret["msg"];

        $update_info = [];
        $update_info["sync_kanke_time"] = date("Y-m-d H:i:s");
        $update_info["sync_kanke_code"] = $code;
        $update_info["sync_kanke_msg"] = $msg;
        $update_info["sync_type"] = "add";

        DB::table("xh_siyu_order")->where(array("id" => $orderInfo["id"]))->update($update_info);

        return compact("code", "msg");

    }

    public static function afterRefundOrder($orderInfo)
    {

        /**
         * @var Student $studentControl
         */
        $studentControl = app(Student::class);
        $params = [];
        $params['order_no'] = $orderInfo['order_num'];
        $params['sy_order_type'] = 1;
        $params['sy_order_num'] = 1;

        // 这里 是 订单
        $params['account'] = $orderInfo["tel"];
        $params["course_id"] = $orderInfo["courseid"];
        $params["unionid"] = $orderInfo["wx_unionid"];

        $ret = $studentControl->openDelete($params);

        $code = $ret["code"];
        $msg = $ret["msg"];

        $update_info = [];
        $update_info["sync_kanke_time"] = date("Y-m-d H:i:s");
        $update_info["sync_kanke_code"] = $code;
        $update_info["sync_kanke_msg"] = $msg;
        $update_info["sync_type"] = "del";

        DB::table("xh_siyu_order")->where(array("id" => $orderInfo["id"]))->update($update_info);

        return compact("code", "msg");

    }

    public function testafterorder(Request $request)
    {
        $orderInfo = DB::table("xh_siyu_order")->where(array("id" => 12))->find();
        try {

            $ret = MyOrder::afterRefundOrder($orderInfo);
            Res::jsonResult($ret);

        } catch (\Throwable $th) {
            throw $th;
        }

    }

}
